<template>
  <el-dialog :visible="modalVisible" :title="formData ? '编辑部门' : '新增部门'" @close="hide">
    <div style="width: 50%; margin-left: 25%">
      <el-form ref="orgEditRef" :model="form_data" label-width="100px" :rules="rules" >
        <el-form-item  label="工号" prop="username">
          <el-input v-model="form_data.username" :disabled="!!formData" style="width:350px"/>
        </el-form-item>
        <el-form-item  label="姓名" prop="name">
          <el-input v-model="form_data.name" :disabled="!!formData" style="width:350px"/>
        </el-form-item>
        <el-form-item label="部门" prop="dept_id">
          <el-select  v-model="form_data.dept_id" placeholder="请选择"  style="width:350px">
            <el-option :value="currentOrg.id" :label="currentOrg.name" style="height: auto">
              <el-tree
                  ref="orgTreeRef"
                  default-expand-all
                  :expand-on-click-node="false"
                  :data="orgTreeData"
                  node-key="id"
                  highlight-current
                  :props="{children: 'children', label: 'name'}"
                  @node-click="handleCheckChange"
              />
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人员类别" prop="persontype_id">
          <el-select v-model="form_data.persontype_id" filterable placeholder="请选择"  style="width:350px">
            <el-option v-for="item in persontypeList"  :key="item.id" :value="item.id" :label="item.name" style="height: auto">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="岗位" prop="post_id">
          <el-select v-model="form_data.post_id" filterable placeholder="请选择"  style="width:350px">
            <el-option v-for="item in posttypeList"  :key="item.id" :value="item.id" :label="item.name" style="height: auto">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select v-model="form_data.role_id" filterable placeholder="请选择"  style="width:350px">
            <el-option v-for="item in roletypeList"  :key="item.id" :value="item.id" :label="item.name" style="height: auto">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="modalVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {deptList} from '@/utils/dept';
import {postList} from "@/utils/post";
import {personType} from "@/utils/personType"
import {roleList} from "@/utils/role"
import {userAdd,userEdit} from "@/utils/user"

export default {
  name: 'EditStaff',
  props: {
    formData: {
      type: Object,
      default: null
    }
  },
  data() {
    const validateId = (rule, value, callback) => {
      if (this.form_data.dept_id !== '' && this.form_data.dept_id !== undefined) {
        callback()
      } else {
        callback(new Error('部门不能为空'));
      }
    };
    return {
      peopleList:[],
      persontypeList:[],
      posttypeList:[],
      roletypeList:[],
      modalVisible: false,
      form_data: {},
      orgTreeData: [],
      currentOrg: {},
      rules: {
        username: [
          {
            required: true, message: '请输入工号', trigger: 'blur'
          }
        ],
        dept_id: [
          {
            required: true, validator: validateId
          }
        ],
        name: [
          {
            required: true, message: '请输入姓名', trigger: 'blur'
          }
        ],
        persontype_id: [
          {
            required: true, message: '请选择人员类别', trigger: 'blur'
          }
        ],
        post_id: [
          {
            required: true, message: '请选择岗位', trigger: 'blur'
          }
        ],
        role_id: [
          {
            required: true, message: '请选择角色', trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    formData: {
      immediate: true,
      deep: true,
      handler(n, o) {
        if (n && n !== o) {
          this.form_data = JSON.parse(JSON.stringify(n))
        } else {
          this.form_data = {
          };
        }
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init(){
      postList().then(res=>{
        if(res.code === "1"){
          this.posttypeList = res.data
        }
      })
      roleList().then(res=>{
        if(res.code === "1"){
          this.roletypeList = res.data
        }
      })
      personType().then(res=>{
        if(res.code === "1"){
          this.persontypeList = res.data
        }
      })
    },
    handleSubmit() {
      this.$refs['orgEditRef'].validate((res) => {
        if (res) {
          if(!this.formData){
            console.log('新增')
            const requestBody = {
              ...this.form_data
            };
            console.log('this.form_data',requestBody)
            userAdd(requestBody).then(res => {
              if (res.code === "1") {
                this.$message.success(res.message);
                this.$emit('callback');
                this.hide();
              }else{
                this.$message.error(res.message)
              }
            });
          }else{
            console.log('编辑')
            delete this.form_data.id
            delete this.form_data.role__name
            delete this.form_data.post__name
            delete this.form_data.persontype__name
            delete this.form_data.dept__name
            delete this.form_data.is_active
            const requestBody = {
              ...this.form_data
            };
            console.log('this.form_data',requestBody)
            userEdit(requestBody).then(res => {
              if (res.code === "1") {
                this.$message.success(res.message);
                this.$emit('callback');
                this.hide();
              }else{
                this.$message.error(res.message)
              }
            });
          }
        }
      });
    },
    handleCheckChange(data) {
      // if (!this.formData) {
        this.currentOrg = data;
        this.form_data.dept_id = data.id;
      // }
    },
    recursionGet(data, valueId) { //递归
      let value = null;
      for (let index = 0; index < data.length; index += 1) {
        if (data[index].id === valueId) {
          value = data[index];
          break;
        }
        if (data[index].children instanceof Array && data[index].children.length > 0) {
          const text = this.recursionGet(data[index].children, valueId);
          if (text) {
            return text;
          }
        }
      }
      return value;
    },
    showDialog(){
      this.modalVisible = true;
      this.getOrgTree();
    },
    hide() {
      this.currentOrg = {};
      this.$refs['orgEditRef'].resetFields();
      this.modalVisible = false;
      this.$emit('callback');
    },
    getOrgTree() {
      deptList({}).then(res => {
        if (res.code === 1) {
          this.orgTreeData = [{
            id: 1,
            name: '淮南分公司',
            children: res.data
          }];
          if (this.form_data.dept_id !== '' && this.form_data.dept_id !== undefined && this.form_data.dept_id !== null) {
            this.currentOrg = this.recursionGet(this.orgTreeData, this.form_data.dept_id)
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
